const app = getApp()
var flag = false;
var imageList=null;

var form_data;
Page({
  data: {
    addressId:"",
    addressUserName: "",
    addressBuyerPhone: "",
    addressArea: "",
    addressDetail: "",
    recommendedPrice:"",
    category2Name:"",
    orderRemark: "",

   
    
    
    display1: "flex",
    display2: "none",
    
    
    //////////////////////////////////////预约
    //日期
    timeList: [],
    //可预约天数
    yyDay: 14,
    //预约时间段
    hourList: [{ hour: "8:00", n: 8, isShow: true },
    { hour: "9:00", n: 9, isShow: true },
    { hour: "10:00", n: 10, isShow: true },
    { hour: "12:00", n: 11, isShow: true },
    { hour: "13:00", n: 13, isShow: true },
    { hour: "14:00", n: 14, isShow: true },
    { hour: "15:00", n: 15, isShow: true },
    { hour: "16:00", n: 16, isShow: true },
    { hour: "17:00", n: 17, isShow: true },
    { hour: "18:00", n: 18, isShow: true },
    { hour: "19:00", n: 19, isShow: true }
    ],
    //是否显示
    timeShow: false,
    currentTab: 0,
    //选择时间
    chooseHour: "",
    //选择日期
    chooseTime: "",
    hourIndex: -1,
    //预约时间
    yyTime: ''
    ///////////////////////////////////////
  },
  ////////////////////////////////////////预约时间
  //弹出按钮
  showTimeModel: function () {
    this.setData({
      timeShow: !this.data.timeShow,
      chooseTime: this.data.timeList[0].date,
    });
  },
  //点击外部取消
  modelCancel: function () {
    this.setData({
      timeShow: !this.data.timeShow,
      chooseTime: this.data.timeList[0].date,
    });
  },
  //日期选择
  timeClick: function (e) {
    //非今天-不判断超过当前时间点(所有时间点都可选择)
    if (e.currentTarget.dataset.index != 0) {
      var list = this.data.hourList;
      for (var i = 0; i < list.length; i++) {
        list[i].isShow = true;
      }
      this.setData({
        hourList: list
      })
    } else {
      //今天-过时不可预约
      var hour = new Date().getHours();
      for (var i = 0; i < this.data.hourList.length; i++) {
        var list = this.data.hourList;
        if (this.data.hourList[i].n <= hour) {
          list[i].isShow = false;
          this.setData({
            hourList: list
          })
        }
      }
    }
    this.setData({
      currentTab: e.currentTarget.dataset.index,
      chooseTime: this.data.timeList[e.currentTarget.dataset.index].date,
      yyTime: '',
      chooseHour: "",
      hourIndex: -1
    });
    console.log(this.data.chooseTime)
  },
  // 时间选择
  hourClick: function (e) {
    var that = this;
    // 时间不可选择
    if (!e.currentTarget.dataset.isshow) {
      return false;
    }
    this.setData({
      hourIndex: e.currentTarget.dataset.index,
      chooseHour: this.data.hourList[e.currentTarget.dataset.index].hour,

    });
    var chooseTime = new Date().getFullYear() + "-" + this.data.chooseTime + " " + this.data.chooseHour
    this.setData({
      yyTime: chooseTime
    })
    console.log(chooseTime)
  },

  ///////////////////////////////////////
  toChooseAddre: function () {
    wx.navigateTo({
      //url: '../address/toaddress/toaddress'
      url: '../address/chooseAddre/chooseAddre'
    });
  },
   onLoad: function (options) {
    ///////////////////////////////////////////////预约时间
    Date.prototype.Format = function (format) {
      var o = {
        "M+": this.getMonth() + 1,  //month
        "d+": this.getDate(),     //day
        "h+": this.getHours(),    //hour
        "m+": this.getMinutes(),  //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
        "S": this.getMilliseconds() //millisecond
      }
      if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
      }
      for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
          format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
      }
      return format;
    }
    Date.prototype.DateAdd = function (interval, number) {
      number = parseInt(number);
      var date = new Date(this.getTime());
      switch (interval) {
        case "y": date.setFullYear(this.getFullYear() + number); break;
        case "m": date.setMonth(this.getMonth() + number); break;
        case "d": date.setDate(this.getDate() + number); break;
        case "w": date.setDate(this.getDate() + 7 * number); break;
        case "h": date.setHours(this.getHours() + number); break;
        case "n": date.setMinutes(this.getMinutes() + number); break;
        case "s": date.setSeconds(this.getSeconds() + number); break;
        case "l": date.setMilliseconds(this.getMilliseconds() + number); break;
      }
      return date;
    }



    var dateList = [];
    var now = new Date();
    for (var i = 0; i < this.data.yyDay; i++) {
      var d = {};
      var day = new Date().DateAdd('d', i).getDay();
      if (day == 1) { var w = "周一" }
      if (day == 2) { var w = "周二" }
      if (day == 3) { var w = "周三" }
      if (day == 4) { var w = "周四" }
      if (day == 5) { var w = "周五" }
      if (day == 6) { var w = "周六" }
      if (day == 0) { var w = "周日" }
      d.name = w;
      d.date = new Date().DateAdd('d', i).Format("MM-dd");
      dateList.push(d)
    }
    this.setData({
      timeList: dateList
    });
    //初始化判断
    //当前时间
    var hour = new Date().getHours();

    for (var i = 0; i < this.data.hourList.length; i++) {
      var list = this.data.hourList;
      //过时不可选
      if (this.data.hourList[i].n <= hour) {
        list[i].isShow = false;
        this.setData({
          hourList: list
        })
      }
    }

    //////////////////////////////////////////////////
  },
  onShow:function(options){
    var flag = wx.getStorageSync("flag");
    console.log("..." + flag)
    if (!flag) {
      this.setData({
        display1: "flex",
        display2: "none",
      })

    } else {
      this.setData({
        display1: "none",
        display2: "flex",
        addressId: wx.getStorageSync("addressId"),
        addressUserName: wx.getStorageSync("addressUserName"),
        addressBuyerPhone: wx.getStorageSync("addressBuyerPhone"),
        addressArea: wx.getStorageSync("addressArea"),
        addressDetail: wx.getStorageSync("addressDetail")
      })
    }
    
    var that = this
    //页面初始化，option为页面跳转所带来的参数
    
    var category2Id = wx.getStorageSync("category2ToOrder");
    var openid = wx.getStorageSync("openid");
    console.log("类型2ID", category2Id)
    console.log("openid", openid)
    wx.request({
      url: app.globalData.baseUrl +'/category2/getcategory2byid',
      method: 'GET',
      data: { "category2Id": category2Id },//传入的参数
      success: function (res) {
        var list = res.data.category2;
        if (list == null) {
          var toastText = '获取数据失败' + res.data.errMsg;
          wx.showToast({
            title: toastText,
            icon: '',
            duration: 2000
          });
        } else {
          that.setData({
            //category2Items: list
            category2Id: list.category2Id,
            category2Name: list.category2Name,
            recommendedPrice: list.recommendedPrice
          });
        }
      }
    })
  } ,

 
  //点击立即预约
  formSubmit: function (e) {
    var warn = "";//弹框时提示的内容
    var flag = true;//判断信息输入是否完整
    //判断的顺序依次是：姓名-手机号-地址-具体地址-预约日期-预约时间-开荒面积
    if (this.data.addressUserName == "") {
      warn = "请输入您的地址信息";
    } else if (this.data.yyTime == '') {
      warn = "请选择预约日期";
    }  else {

      flag = false;//若必要信息都填写，则不用弹框，且页面可以进行跳转
      var that = this;
      

     





      ///////////////////操作数据库，插入订单
      
      var amount=0;
      if (e.detail.value.recommendedPrice==undefined){
        amount = that.data.recommendedPrice;
      }else{
        amount = e.detail.value.recommendedPrice;
      }
      console.log('amount：', amount);
      console.log('imageList：', imageList);
      /*wx.request({
        url: app.globalData.baseUrl +'/order/orderinsert',
        data: {//获取数据传到后台
          serviceTime: that.data.yyTime,
          addressId: that.data.addressId,
          //orderAmount: that.data.recommendedPrice,
          orderAmount: amount,
          orderRemark: e.detail.value.orderRemark,
          category2Id: wx.getStorageSync("category2ToOrder"),
          imageList: imageList
        },
        method: "POST",
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },      
        success: function (res) {
          var result = res.data.success
          console.log('result：', res.data.success);
          console.log('serviceTime：', that.data.yyTime);
          console.log('addressId：', that.data.addressId);
          console.log('orderAmount：', e.detail.value.recommendedPrice);
          console.log('orderRemark：', that.data.orderRemark);
          var toastText = "操作成功！";
          if (result != true) {
            toastText = "信息不全" + res.data.errMsg;
          }
          wx.showToast({
            title: toastText,
            icon: '',
            duration: 2000                        
          });
          if(result==true){           
            wx.redirectTo({
                url: '../order/confirm/index'

              })

            
          }
          
          
        }
      })*/

      /////////////////////////////////////////////上传图片
      if (imageList == null) {//当上传图片为0时，只提交表单的文字信息
        wx.request({
          url: app.globalData.baseUrl + '/order/orderinsert',
          data: {//获取数据传到后台
            serviceTime: that.data.yyTime,
            addressId: that.data.addressId,
            //orderAmount: that.data.recommendedPrice,
            orderAmount: amount,
            orderRemark: e.detail.value.orderRemark,
            category2Id: wx.getStorageSync("category2ToOrder"),
            imageList: null
          },
          method: "POST",
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: function (res) {
            var result = res.data.success
            console.log('result：', res.data.success);
            console.log('serviceTime：', that.data.yyTime);
            console.log('addressId：', that.data.addressId);
            console.log('orderAmount：', e.detail.value.recommendedPrice);
            console.log('orderRemark：', that.data.orderRemark);
            var toastText = "操作成功！";
            if (result == false) {
              toastText = "信息不全" ;
            }
            if (result != "fail"){
              wx.showToast({
                title: toastText,
                icon: '',
                duration: 2000
              });
            }
            
            if (result == true) {
              wx.redirectTo({
                url: '../order/confirm/index'

              })
            }
            var flag1 = false;
            if (result == "fail") {
              flag1 = true;
              warn = "由于被投诉存在不当行为，您的账号被封禁了，如有疑问请联系客服处理：888888888" ;
            }
            /*wx.showToast({
              title: toastText,
              icon: '',
              duration: 2000
            });*/

            if (flag1 == true) {
              wx.showModal({
                title: '提示',
                content: warn
              })
            }


          }
        })
      }else{
        console.log("upload图片列表", imageList.length);
        var that = this;
        var images_list = []; //设置了一个空数组进行储存服务器端图片路径
        for (var i = 0; i < imageList.length; i++) {
          wx.uploadFile({
            url: app.globalData.baseUrl + '/order/upload',
            filePath: imageList[i],
            name: 'file',
            formData: null,
            success: function (res) {
              console.log(res.data)
              //console.log(res.data)
              //后端返回图片上传到服务器上边的地址的json
              //图片json转换数组
              var jsonObj = JSON.parse(res.data)
              console.log(jsonObj.url)
              images_list.push(jsonObj.url);
              if (imageList.length == images_list.length) {//只有当图片全部上传成功才能提交表单，因为表单只需要提交一次
                var images_str = images_list.join(",")//把存放图片地址的数组转化为以逗号分隔的字符串
                console.log("images_str:",images_str)
                wx.request({
                  url: app.globalData.baseUrl + '/order/orderinsert',
                  method: 'POST',
                  data: {
                    serviceTime: that.data.yyTime,
                    addressId: that.data.addressId,
                    //orderAmount: that.data.recommendedPrice,
                    orderAmount: amount,
                    orderRemark: e.detail.value.orderRemark,
                    category2Id: wx.getStorageSync("category2ToOrder"),
                    imageList: images_str
                  },
                  header: {
                    "Content-Type": "application/x-www-form-urlencoded" // 默认值
                  },
                  success(res) {//success只能说明接口调取并返回成功，并不是代表信息上传成功，还需要判断返回的信息
                    var result = res.data.success
                    console.log('result：', res.data.success);
                    console.log('serviceTime：', that.data.yyTime);
                    console.log('addressId：', that.data.addressId);
                    console.log('orderAmount：', e.detail.value.recommendedPrice);
                    console.log('orderRemark：', that.data.orderRemark);
                    var toastText = "操作成功！";
                    if (result != true) {
                      toastText = "信息不全" + res.data.errMsg;
                    }
                    wx.showToast({
                      title: toastText,
                      icon: '',
                      duration: 2000
                    });
                    if (result == true) {
                      wx.redirectTo({
                        url: '../order/confirm/index'

                      })
                    }

                    imageList=null;

                  }
                })
              }
              
            },
            fail: function (error) { }
          })
        }
        
      }
      
          
           
           
              

    

    }
    //如果信息填写不完整，弹出输入框
    if (flag == true) {
      wx.showModal({
        title: '提示',
        content: warn
      })



    }


  },
  
  getImageList(e) {
    let that = this;
    console.log("获取上传图片");
    //console.log(e.detail);
    imageList = e.detail;
    console.log("图片列表",imageList);

  },

  ///////////上传图片
  upload: function () {
    console.log("upload图片列表", imageList.length);
    var that = this;
    var images_list = []; //设置了一个空数组进行储存服务器端图片路径
    for (var i = 0; i < imageList.length; i++) {
      wx.uploadFile({
        url: app.globalData.baseUrl +'/order/upload',
        filePath: imageList[i],
        name: 'file',
        formData: null,
        success: function (res) {
          console.log(res.data)
          //console.log(res.data)
          //后端返回图片上传到服务器上边的地址的json
          //图片json转换数组
          var jsonObj = JSON.parse(res.data)
          console.log(jsonObj.url)
          images_list.push(jsonObj.url);
          if (imageList.length == images_list.length) {//只有当图片全部上传成功才能提交表单，因为表单只需要提交一次
            var images_str = images_list.join(",")//把存放图片地址的数组转化为以逗号分隔的字符串
            console.log(images_str)
            wx.request({
              url: app.globalData.baseUrl + '/order/orderinsert',
              method: 'POST',
              data: {
                serviceTime: that.data.yyTime,
                addressId: that.data.addressId,
                //orderAmount: that.data.recommendedPrice,
                orderAmount: amount,
                orderRemark: e.detail.value.orderRemark,
                category2Id: wx.getStorageSync("category2ToOrder"),
                imageList: images_str
              },
              header: {
                "Content-Type": "application/x-www-form-urlencoded" // 默认值
              },
              success(res) {//success只能说明接口调取并返回成功，并不是代表信息上传成功，还需要判断返回的信息
                var result = res.data.success
                console.log('result：', res.data.success);
                console.log('serviceTime：', that.data.yyTime);
                console.log('addressId：', that.data.addressId);
                console.log('orderAmount：', e.detail.value.recommendedPrice);
                console.log('orderRemark：', that.data.orderRemark);
                var toastText = "操作成功！";
                if (result != true) {
                  toastText = "信息不全" + res.data.errMsg;
                }
                wx.showToast({
                  title: toastText,
                  icon: '',
                  duration: 2000
                });
                if (result == true) {
                  wx.redirectTo({
                    url: '../order/confirm/index'

                  })


                }

              }
            })
          }
         /* if (res) {
            wx.showToast({
              title: '下单成功！',
              duration: 3000
            });
            
              wx.redirectTo({
                url: '../order/confirm/index'

              })


            
          }*/
        },
        fail: function (error) { }
      })
    }
    /*this.setData({
      formdata: ''
    })*/
  }

})


